import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/widgets/widget.dart';

import '../index.dart';

class DetailContent extends GetView<ContentDetailController> {
  const DetailContent({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(15),
      child: GetBuilder<ContentDetailController>(
        id: 'contentInfo',
        builder: (_) => UserInfoCell(
          avatarHeroTag: '${_.state.uniqueTag}_${_.state.noteId}',
          avatar: _.state.userAvatar ?? _.state.contentInfo.avatar,
          name: _.state.contentInfo.customerName ?? '',
          showNameAuth: _.state.contentInfo.officialFlag == 1,
          nameAuthText: _.state.contentInfo.officialName,
          groupName: _.state.contentInfo.groupName,
          isBottomGroup: true,
          region:
              '${_.state.contentInfo.provinceName ?? ''}${_.state.contentInfo.cityName ?? ''}',
          dateTime: _.state.contentInfo.createTime,
          bottomChild: _buildDetailContent(),
          rightChild: _.state.contentInfo.isMy != 1
              ? GetBuilder<ContentDetailController>(
                  id: 'btn',
                  builder: (_) => _buildBtn(
                    text: _.state.contentInfo.followFlag == 1
                        ? '已关注'.tr
                        : '关注'.tr,
                    isOutline: _.state.contentInfo.followFlag == 1,
                    onPressed: () => _.onFollowHandle(),
                  ),
                )
              : const SizedBox.shrink(),
          onGroupTap: () => _.toGroupDetailPage(),
          onUserTap: () => _.toUserDetailPage(_.state.contentInfo.customerId),
        ),
      ),
    );
  }

  Widget _buildBtn({
    required String text,
    bool isOutline = false,
    VoidCallback? onPressed,
  }) {
    Widget btn;
    if (isOutline) {
      btn = OutlinedButton(
        onPressed: onPressed,
        style: OutlinedButton.styleFrom(
          padding: const EdgeInsets.all(0),
          side: const BorderSide(color: AppColors.danger, width: 1),
          foregroundColor: Colors.white,
          enableFeedback: true,
        ),
        child: Text(
          text,
          style: const TextStyle(color: AppColors.danger, fontSize: 12),
        ),
      );
    } else {
      btn = ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.all(0),
          backgroundColor: AppColors.danger,
          foregroundColor: Colors.white,
          enableFeedback: true,
        ),
        child: Text(
          text,
          style: const TextStyle(color: Colors.white, fontSize: 12),
        ),
      );
    }

    return SizedBox(
      width: 62,
      height: 24,
      child: btn,
    );
  }

  /// 详情正文
  Widget _buildDetailContent() {
    var info = controller.state.contentInfo;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (info.text != null && info.text!.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 6),
            child: ContentCardText(
              info.text!,
              maxLines: 1000,
            ),
          ),
        if (info.audio != null && info.audio!.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 12),
            child: Obx(
              () => AudioWaveWidget(
                isPlaying: controller.state.isAudioPlaying.value &&
                    info.audio == controller.state.playingUrl.value,
                duration: info.audioDuration ?? 0,
                durationChild: Obx(
                  () => AudioWaveDurationText(
                    '${info.audio == controller.state.playingUrl.value ? controller.state.audioSeconds.value : (info.audioDuration ?? 0)}s',
                  ),
                ),
                onTap: () => controller.toggleAudioPlay(
                    info.audio!, info.audioDuration ?? 0),
              ),
            ),
          ),
        if (info.video != null && info.video!.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 12),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: GetBuilder<ContentDetailController>(
                id: 'videoPlayer',
                builder: (_) {
                  if (_.state.flickManager != null) {
                    return FlickVideoPlayer(
                      flickManager: _.state.flickManager!,
                    );
                  }
                  return const AspectRatio(aspectRatio: 16 / 19);
                },
              ),
            ),
          ),
        if (info.image != null && info.image!.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(top: 6),
            child: Column(
              children: info.image!.map((cover) {
                return GestureDetector(
                  onTap: () => controller.handlePreviewImages(
                    info.image!,
                    cover,
                  ),
                  child: _buildImageItem(cover),
                );
              }).toList(),
            ),
          ),
      ],
    );
  }

  Widget _buildImageItem(String cover) {
    Widget rectImage = ClipRRect(
      borderRadius: BorderRadius.circular(6),
      child: CustomImage(url: cover),
    );

    // 图片路径中获取宽高
    var sizeInfo = Util.getUrlParams(cover);
    if (sizeInfo.isNotEmpty && sizeInfo['w'] != null || sizeInfo['h'] != null) {
      // 原始图片宽高
      double? w = double.tryParse(sizeInfo['w']!);
      double? h = double.tryParse(sizeInfo['h']!);
      if (w != null && h != null) {
        return Container(
          margin: const EdgeInsets.only(top: 6),
          child: AspectRatio(
            aspectRatio: w / h,
            child: rectImage,
          ),
        );
      }
    }
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.only(top: 6),
      child: rectImage,
    );
  }
}
